﻿package string;

public class 替换字符串中连续出现的指定字符串 {

	public static String replace(String str, String from, String to) {
		if (str == null || from == null || str.equals("") || from.equals("")) {
			return str;
		}
		char[] chas = str.toCharArray();
		char[] froms = from.toCharArray();
		int count = 0;
		int M = froms.length;
		for (int i = 0; i < chas.length; i++) {
			if (chas[i] == froms[count++]) {
				if (count == M) {
					clear(chas, i, froms.length);
					count = 0;
				}
			} else {
				count = 0;// 重新配置
			}

		}
		String res = "";
		String cur = "";
		for (int i = 0; i < chas.length; i++) {
			// 把原串中剩下的字符链接起来
			if (chas[i] != 0) {
				cur = cur + String.valueOf(chas[i]);
			}
			// 绑定to(在最有一个字符是0的时候，才开始将to追加起来)
			if (chas[i] == 0 && (i == 0 || chas[i - 1] != 0)) {
				res = res + cur + to;
				cur = "";
			}
		}
		if (!cur.equals(""))
			res = res + cur;

		return res;
	}

	/**
	 * 这里的length是小于end的，不用担心溢出的问题
	 * 
	 * @param chas
	 * @param end
	 * @param length
	 */
	private static void clear(char[] chas, int end, int length) {
		while (length-- != 0) {
			chas[end--] = 0;
		}
	}

	public static void main(String[] args) {
		System.out.println(replace("acdsdsss","acd","123232"));

	}

}
